package cn.lyz.authority.config;

import cn.lyz.authority.common.vo.LyzResponseBody;
import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.security.authentication.InsufficientAuthenticationException;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.nio.charset.StandardCharsets;

@Component
public class AuthenticationEntryPointImpl implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException ex) throws IOException, ServletException {
        LyzResponseBody<Object> responseBody;
        if(ex instanceof InsufficientAuthenticationException){
            responseBody = LyzResponseBody.error(ex).setMsg("认证失败，请重新登录");
        }else{
            responseBody = LyzResponseBody.error(ex);
        }
        responseBody.setCode(HttpStatus.UNAUTHORIZED.value());
        String s = new ObjectMapper().writeValueAsString(responseBody);
        response.setStatus(HttpStatus.OK.value());
        response.setCharacterEncoding(StandardCharsets.UTF_8.name());
        response.setContentType(MediaType.APPLICATION_JSON_VALUE);
        response.getWriter().println(s);
    }
}
